<template>
  <div class="choosefill">
    <v-header>
      <div slot="collect" @click="toggleCollect">
        <img :src="isFavorite? Favorited : Favorite" alt="">
      </div>
      <div slot="note" @click="shownote = true">添加笔记</div>
      <div slot="up" @click="submit" v-show="!showAnswer">提交</div>
    </v-header>

    <div class="choose-con" v-show="show">
      <p class="con-tit">选词填空</p>
      <p class="con-tit">* 本题备选项需点击原文空格处获取,在列表上点击即可。</p>
      <!-- 判断做题  还是 做题记录 -->
      <div class="con-fill" v-if="!showAnswer" id="fill" v-html="this.content"></div>
      <div class="con-fill" v-else id="record" v-html="this.content"></div>

      <div class="analyse" v-show="showAnswer">
        <p>答案解析:</p>
        <div class="detail" v-for="(item,index) in answer" :key="index">({{index+1}}) {{item}}</div>
      </div>
    </div>

    <!-- 添加笔记 -->
    <van-dialog v-model="shownote" title="复习笔记" showCancelButton confirmButtonText="保存" :beforeClose="noteBtn">
      <textarea v-model="message" placeholder="要记点什么吗"></textarea>
    </van-dialog>

    <!-- 点击填空 -->
    <van-dialog v-model="blanks" :showConfirmButton="false" close-on-click-overlay>
      <div class="list">
        <div class="list-col" v-for="(item,index) in options" :key="index" @click="tofill(item.value,item.id)">{{nums[index]}}. {{item.value}}</div>
      </div>
    </van-dialog>

  </div>
</template>

<script>
import header from '@/components/content/header'
import { Toast, Dialog } from 'vant'
import { mapGetters } from 'vuex'
import api from '@/api/api'

export default {
  name: 'choosefill',
  components: {
    "v-header":header,
    [Toast.name]: Toast,
    [Dialog.Component.name]: Dialog.Component,
  },
  data () {
    return {
      isFavorite:false,  // 是否已收藏
      Favorite:require('@/assets/collect.png'),
      Favorited:require('@/assets/collected.png'),
      message:'',  // 添加笔记内容
      shownote:false,
      blanks:false,
      prevRoute:'',
      content:'',   // 选词填空的文章内容
      answer:[],  // 答案的数组
      options:[],  // 选项数组
      nums:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q'],  // 选项前的标签
      show:false,
      target:'',  //存储点击的位置
      reglength:'',  //匹配个数
      reglength2:'',  //匹配个数
      fillarr:[],  // 提交答案的数组 内容
      fill:{},  // 提交答案的对象 索引
    }
  },
  created () {
    this.getContent()
    window.changeFill=this.changeFill
  },
  mounted () {
  },
  computed: {
    ...mapGetters(['showAnswer','chooseAnswer']),
  },
  beforeRouteEnter(to, from, next) {
    // console.log(from)
    next(vm => {
      vm.geturl(from.name)
    })
  },
  methods: {
    // 初始化文章内容
    async getContent(){
      Toast.loading({message: '加载中...', forbidClick: true});
      await api.Choosefill().then(res=>{
        Toast.clear()
        this.show = true
        // console.log(res)
        this.content = res.data.content
        // console.log(this.content)
        this.answer = res.data.answer
        this.options = res.data.options
        // console.log(this.options)
      }).catch(error=>{
        console.log(error)
      })
      this.$nextTick(() => {
        if(!this.showAnswer){
          this.replaceLine()
        }else{
          this.replaceLine2() // 这个是做题记录的
        }
      })
    },

    // 文章下划线替换
    replaceLine(){
      let str = document.querySelector("#fill").innerHTML;  // 这个是做题 的
      // console.log('文本',str)
      let reg = /[__]{2,10}/g;  //匹配下划线长度2-10
      this.reglength = str.match(reg).length   //获取匹配个数
      console.log('匹配个数',this.reglength)
      var txt = str.replace(reg,()=>{
        return `<span onclick="changeFill(event)" class="underline">点击填空</span>`
      })
      document.querySelector("#fill").innerHTML = txt;
    },

    // (做题记录)文章下划线替换  然后 替换答案
    replaceLine2(){
      let recordstr = document.querySelector("#record").innerHTML;  // 这个是做题记录 的
      // console.log('文本',recordstr)
      let reg2 = /[__]{2,10}/g;  //匹配下划线长度2-10
      this.reglength2 = recordstr.match(reg2).length   //获取匹配个数
      console.log('匹配个数',this.reglength2)
      var recordtxt = recordstr.replace(reg2,()=>{
        return `<span class="underline2">点击填空</span>`
      })
      document.querySelector("#record").innerHTML = recordtxt;
      // 答案替换
      for(let i=0;i<this.reglength2;i++){
        document.querySelectorAll(".underline2")[i].innerHTML=this.chooseAnswer[i]
      }
    },

    // 收藏    没写返回数据给后台
    toggleCollect(){
      if( this.isFavorite ){
        this.isFavorite = false
        Toast('取消收藏')
      }else{
        this.isFavorite = true
        Toast('收藏成功')
      }
    },

    // 点击填空
    changeFill(e){
      this.blanks = true
      this.target = e.target
      // console.log(this.target)
    },
    // 填值
    tofill(value,id){
      // console.log(value,id)
      this.blanks = false
      this.target.innerHTML = value
    },

    // 添加笔记
    noteBtn(action,done){
      if(action === 'cancel'){
        this.shownote = false
        done()
      }else if (action === 'confirm'){
        if(!this.message){
          Toast("请输入笔记,再保存")
          done(false)
        }else{
          console.log('选词填空笔记:',this.message)
          this.shownote = false
          this.message = ''
          done()
        }
      }
    },

    // 提交
    submit(){
      Dialog.confirm({message: '是否提交试题?',}).then(() => {
        Toast.success('提交成功')
        setTimeout(() => {
          var label =document.querySelectorAll(".underline");
          for(let i=0;i<this.reglength;i++){
            if(label[i].innerText == '点击填空'){
              this.fillarr[i] = '未作答'
              this.fill[i] = '未作答'
            }else{
              this.fillarr[i] =label[i].innerText
              this.fill[i] =label[i].innerText
            }
          }
          console.log('选词填空',this.fillarr)
          this.$store.dispatch("chooseAnswer", this.fill)
          this.$router.push({path:'/reportfill'})
        }, 2000);
      })
      .catch(() => {
        // 取消
      });
    },

    geturl(url){
      this.prevRoute=url;
      // console.log(this.prevRoute)
      if(url == "readtype"){
        this.$store.dispatch("showAnswer", false)
      }
    }

  }

}
</script>

<style lang="less" scoped>
textarea{
  font-size: 14px;
  width: 100%;
  white-space: pre-wrap;
  display: block;
  width: 100%;
  height: 100%;
  text-align: justify;
  box-sizing: border-box;
  border: 0;
  resize: none;
  line-height: 24px;
  padding: 10px 10px 10px 20px;
  color: #323232;
  height: 150px;
}
.choose-con{
  margin: 5px 0 40px;
  padding: 10px;
  .con-tit{font-size: 16px;color: #333;line-height: 24px;}
}
.con-fill{
  text-align: justify;
  font-size: 16px;
  color: #333;
  line-height: 24px;
}
.analyse{
  font-size: 16px;
  color: #333;
  margin-top: 20px;
  .detail{
    text-align: justify;
    line-height: 24px;
    margin: 15px 0;
  }
}
/deep/.underline,/deep/.underline2{
  border-bottom: 1px solid #999;
  display: inline-block;
  padding: 0 10px;
  text-indent: 0;
  color: #999;
  font-size: 14px;
  height: 16px;
  line-height: 16px;
  vertical-align: middle;
}
.list{
  height: 250px;
  box-sizing: border-box;
  padding: 20px 20px;
  overflow-y: auto;
  .list-col{
    color: #323232;
    font-size: 16px;
    line-height: 36px;
    margin-bottom: 10px;
  }
  .list-col:last-child{margin-bottom: 0;}
}
</style>
